package com.formiaomiao.demain.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.formiaomiao.demain.R;
import com.formiaomiao.demain.adapter.ContactAdapter;
import com.formiaomiao.demain.base.BaseActivity;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.model.FriendDetailBean;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.weight.DividerItemDecoration;
import com.formiaomiao.demain.weight.LetterView;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FriendActivity extends BaseActivity implements LetterView.CharacterClickListener,
    ContactAdapter.onItemClickListener{

    @BindView(R.id.iv_class_back)
    ImageView ivClassBack;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.contact_list)
    RecyclerView contactList;
    @BindView(R.id.letter_view)
    LetterView letterView;

    ContactAdapter adapter;
    FriendDetailBean friendDetailBean = new FriendDetailBean();
    List<String> mContactNames = new ArrayList<>();
    List<String> mContactimgs = new ArrayList<>();
    List<FriendDetailBean.DataBean> friendDetailBeanList = new ArrayList<>();

    StringBuffer sb = new StringBuffer();
    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        ViewInit();
    }

    private void ViewInit() {
        tvClassName.setText("通讯录");
        layoutManager = new LinearLayoutManager(this);
        contactList.setLayoutManager(layoutManager);
        contactList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        letterView.setCharacterListener(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                    sb.append("{\"userid\":"+StaticValues.userid+",\"data\":[");
                    for (int i = 0; i < usernames.size(); i++) {
                        sb.append("{\"username\":\""+usernames.get(i)+"\"},");
                    }
                    sb.delete(sb.length()-1,sb.length());
                    sb.append("]}");
                    FriendDataInit(sb.toString());
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvents(MessageEvent msg) {
        if (msg.getMessage().equals("好友关系变更")) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                        sb.append("{\"userid\":"+StaticValues.userid+",\"data\":[");
                        for (int i = 0; i < usernames.size(); i++) {
                            sb.append("{\"username\":\""+usernames.get(i)+"\"},");
                        }
                        sb.delete(sb.length()-1,sb.length());
                        sb.append("]}");
                        FriendDataInit(sb.toString());
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }else if(msg.getMessage().startsWith("备注:")){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                        sb.append("{\"userid\":"+StaticValues.userid+",\"data\":[");
                        for (int i = 0; i < usernames.size(); i++) {
                            sb.append("{\"username\":\""+usernames.get(i)+"\"},");
                        }
                        sb.delete(sb.length()-1,sb.length());
                        sb.append("]}");
                        FriendDataInit(sb.toString());
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    /**
     * 获取用户详情
     * @param json
     */
    private void FriendDataInit(String json){
        OkGo.<String>post(BaseUrl.USERFRIENDDETAIL).params("usernamejson",json)
                .headers("Authorization", PreferenceUtils.getString(this, PreferenceValues.TOKEN))
                .tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                mContactNames.clear();
                mContactimgs.clear();
                friendDetailBeanList.clear();
                friendDetailBean = gson.fromJson(response.body(),FriendDetailBean.class);
                friendDetailBeanList.addAll(friendDetailBean.getData());
                for (int i = 0; i < friendDetailBean.getData().size(); i++) {
                    mContactNames.add(friendDetailBean.getData().get(i).getFriendremarks() == null || friendDetailBean.getData().get(i).getFriendremarks().equals("")
                            ? friendDetailBean.getData().get(i).getNickName() : friendDetailBean.getData().get(i).getFriendremarks());
                    mContactimgs.add(friendDetailBean.getData().get(i).getUserHead());
                }
                adapter = new ContactAdapter(FriendActivity.this,mContactNames,mContactimgs);
                contactList.setAdapter(adapter);
                adapter.setOnItemClickListener(FriendActivity.this);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R.id.iv_class_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void clickCharacter(String character) {
        layoutManager.scrollToPositionWithOffset(adapter.getScrollPosition(character), 0);
    }

    @Override
    public void clickArrow() {
        layoutManager.scrollToPositionWithOffset(0, 0);
    }

    @Override
    public void itemClickListener(View v, int i) {
        Intent intent = new Intent();
        intent.putExtra("id",friendDetailBeanList.get(i).getId());
        intent.putExtra("neteaseUid",friendDetailBeanList.get(i).getNeteaseUid());
        intent.putExtra("nickname",friendDetailBeanList.get(i).getNickName());
        intent.putExtra("userhead",friendDetailBeanList.get(i).getUserHead());
        intent.putExtra("username",friendDetailBeanList.get(i).getUserName());
        intent.putExtra("UnreadMsgCount", 1);
        intent.putExtra("friendremarks", friendDetailBeanList.get(i).getFriendremarks() == null ||
                friendDetailBeanList.get(i).getFriendremarks().equals("") ?
                "" : friendDetailBeanList.get(i).getFriendremarks());
        intent.setClass(FriendActivity.this,ChatActivity.class);
        startActivity(intent);
    }
}
